import React, { useCallback, useContext, useEffect, useState } from "react";
import { getCache, setCache } from "../utils/cache";
import {
  LoginAttribute,
  LocalLoginInfo,
  LoginProviderIpo
} from "../../types/uses/useLogin";

const defalut = { isLogin: false };

export const LOGIN_INFO = "LOGIN_INFO";

/**
 * 获取登录信息
 */
export const getLoginInfo = (): LocalLoginInfo => {
  return (getCache(LOGIN_INFO) || defalut) as LocalLoginInfo;
};

const LoginContext = React.createContext({});

export const useLogin = () => useContext(LoginContext);

const LoginProvider: React.FC<LoginProviderIpo> = <T extends {}>(props) => {
  const [loginState, setLoginState] = useState<{}>(defalut);
  //监听数据变化
  useEffect(() => {
    if (props.loginState) {
      setLoginState(props.loginState);
      setCache(LOGIN_INFO, props.loginState);
    }
  }, [props.loginState]);
  const login = useCallback((res: T) => {
    setLoginState({ ...res });
    setCache(LOGIN_INFO, { ...res });
  }, []);

  const logout = useCallback(() => {
    setLoginState(defalut);
    setCache(LOGIN_INFO, defalut);
  }, []);

  return (
    <LoginContext.Provider
      value={
        {
          state: loginState,
          login,
          logout
        } as LoginAttribute<T>
      }
    >
      {props.children}
    </LoginContext.Provider>
  );
};

export default LoginProvider;
